package com.wo.cloud.auth.sms;

import cn.hutool.core.util.ObjectUtil;
import com.wo.cloud.auth.util.SmsConstant;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2021/5/25 13:59
 * Description: 手机号登录 拦截器
 */
public class SmsCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public SmsCodeAuthenticationFilter() {
        super(new AntPathRequestMatcher(SmsConstant.OAUTH_MOBILE, "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {

        // 获取请求参数值
        String mobile = httpServletRequest.getParameter(SmsConstant.MOBILE);

        if (ObjectUtil.isNull(mobile)){
            mobile =  "";
        }


        mobile = mobile.trim();

        SmsCodeAuthenticationToken smsCodeAuthenticationToken = new SmsCodeAuthenticationToken(mobile);

        // Allow subclasses to set the "details" property
        smsCodeAuthenticationToken.setDetails(authenticationDetailsSource.buildDetails(httpServletRequest));

        return this.getAuthenticationManager().authenticate(smsCodeAuthenticationToken);
    }
}
